package net.adst.ui.mainframe.toppanel;

import net.adst.beans.NaemTec;
import net.adst.beans.OurTecRow;
import net.adst.beans.User;
import net.adst.resources.VariableNames;
import net.adst.searcher.Searcher;
import net.adst.ui.mainframe.tabs.AdstTabPanel;
import net.adst.ui.other.AddItemsDialog;
import net.adst.ui.other.EditPasswordDialog;
import net.adst.ui.other.EditTecDialog;
import net.adst.ui.other.EditUsersDialog;
import net.adst.util.*;
import net.adst.util.fileFilters.MSExcelFilter;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import sun.net.ResourceManager;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 02.11.12
 * Time: 1:50
 * To change this template use File | Settings | File Templates.
 */
public class ButtonsArea extends JPanel {

    private JButton userButton;
    private JButton tecButton;
    private JButton addRowButton;
    private JButton removeButton;
    private JButton saveButton;
    private JButton exlButton;
    private JButton markOurButton;
    private JButton markNaemPaidNamButton;
    private JButton markNaemMoneyOkButton;
    private JButton markNaemMoneyNadoButton;
    private JTextField toplivoField;
    private JButton saveToplivoButton;
    private JButton updateButton;
    private User user;

    public ButtonsArea() {
        setLayout(new GridBagLayout());
        this.user = (User) DataManager.getObject(VariableNames.USER);
        addButtons();
    }

    private void addButtons() {
        userButton = new JButton(user.isAdmin() ? "работа с кадрами" : "изменить пароль");
        userButton.setFocusPainted(false);
        userButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (user.isAdmin()) {
                    EditUsersDialog dialog = new EditUsersDialog(user);
                    dialog.init();
                } else {
                    EditPasswordDialog dialog = new EditPasswordDialog(user);
                    dialog.init();
                }

            }
        });

        tecButton = new JButton("работа с техникой");
        tecButton.setFocusPainted(false);
        tecButton.setToolTipText("Открыть окно для управления техникой.");
        tecButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                EditTecDialog dialog = new EditTecDialog();
                dialog.init();
            }
        });


        addRowButton = new JButton("доб запись");
        addRowButton.setToolTipText("Открыть окно для добавления записей в базу.");
        addRowButton.setFocusPainted(false);
        addRowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                AddItemsDialog dialog = new AddItemsDialog(AdstTabPanel.getIndex());
                dialog.init();

            }
        });

        removeButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/remove.png")));
        removeButton.setFocusPainted(false);
        removeButton.setEnabled(false);
        removeButton.setToolTipText("Удалить запись избазы.");
        DataManager.setObject(VariableNames.UI_TOP_PANEL_REMOVE_BUTTON, removeButton);
        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int response = JOptionPane.showOptionDialog(null, "Вы, действительно хотите удалить запись(си)?", "Удалить?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (response == JOptionPane.NO_OPTION) {
                    return;
                }
                if (response == JOptionPane.YES_OPTION) {
                    MyUtils.removeItem(AdstTabPanel.getIndex());
                }
            }
        });

        saveButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/save.png")));
        saveButton.setFocusPainted(false);
        saveButton.setEnabled(false);
        saveButton.setToolTipText("Сохранить изменения в базу.(Ctrl+S)");
        DataManager.setObject(VariableNames.UI_TOP_PANEL_SAVE_BUTTON, saveButton);
        Action saveAction = new AbstractAction("save") {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (saveButton.isEnabled()) {
                    saveButton.setEnabled(false);
                    MyUtils.saveChanges();
                }
            }
        };
        saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
        saveButton.getActionMap().put("myAction", saveAction);
        saveButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put((KeyStroke) saveAction.getValue(Action.ACCELERATOR_KEY), "myAction");
        saveButton.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        saveButton.setEnabled(false);
                        MyUtils.saveChanges();
//                        Searcher.searchNaem();
//                        Searcher.searchOur();
                    }
                });
        exlButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/excel.png")));
        exlButton.setFocusPainted(false);
        exlButton.setToolTipText("Сохранить результат поиска в новом файле.");
        exlButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveNewExcelAction();
            }
        });

        updateButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/update.png")));
        updateButton.setFocusPainted(false);
        updateButton.setToolTipText("Перезагрузить данные из базы.");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MainDataBuilder.buildData();
                Searcher.searchNaem();
                Searcher.searchOur();
                ((JLabel) DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL)).setVisible(false);
                ((JLabel) DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL)).setVisible(false);
                ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_SAVE_BUTTON)).setEnabled(false);
                JOptionPane.showMessageDialog(null, "Данные успешно перезпгруженны.", "Перезагружено.", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
            }
        });


        markOurButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/money.png")));
        markOurButton.setFocusPainted(false);
        markOurButton.setVisible(false);
        markOurButton.setEnabled(false);
        markOurButton.setToolTipText("Оплачено.");
        DataManager.setObject(VariableNames.UI_TOP_PANEL_MARK_OUR_BUTTON, markOurButton);
        markOurButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel model = (DefaultTableModel) DataManager.getObject(VariableNames.UI_OUR_DETAILED_MODEL);
                JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_OUR_DETAILED_TABLE);
                for (int i = 0; i < detailsTable.getSelectedRows().length; i++) {
                    int selectedRow = detailsTable.getSelectedRows()[i];
                    OurTecRow tec = ((ArrayList<OurTecRow>) DataManager.getObject(VariableNames.TEC_OUR_USING_ROWS)).get(selectedRow);
                    if (tec.getPaidFor()) {
                        tec.setPaidFor(false);
                    } else {
                        tec.setPaidFor(true);
                    }
                }
                saveButton.setEnabled(true);
                model.fireTableDataChanged();
            }
        });
        markNaemPaidNamButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/money.png")));
        markNaemPaidNamButton.setFocusPainted(false);
        markNaemPaidNamButton.setEnabled(false);
        markNaemPaidNamButton.setToolTipText("Оплачено нам.");
        DataManager.setObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_BUTTON, markNaemPaidNamButton);
        markNaemPaidNamButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel model = (DefaultTableModel) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_MODEL);
                JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_TABLE);
                for (int i = 0; i < detailsTable.getSelectedRows().length; i++) {
                    int selectedRow = detailsTable.getSelectedRows()[i];
                    ArrayList<NaemTec> tecs = (ArrayList<NaemTec>) DataManager.getObject(VariableNames.TEC_NAEM_USING_ROWS);
                    NaemTec tec = tecs.get(selectedRow);
                    if (tec.getPaidNam()) {
                        tec.setPaidNam(false);
                    } else {
                        tec.setPaidNam(true);
                    }
                }
                saveButton.setEnabled(true);
                model.fireTableDataChanged();
            }
        });
        markNaemMoneyOkButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/moneyOk.png")));
        markNaemMoneyOkButton.setFocusPainted(false);
        markNaemMoneyOkButton.setEnabled(false);
        markNaemMoneyOkButton.setToolTipText("Мы оплатили.");
        DataManager.setObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_OK_BUTTON, markNaemMoneyOkButton);
        markNaemMoneyOkButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel model = (DefaultTableModel) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_MODEL);
                JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_TABLE);
                for (int i = 0; i < detailsTable.getSelectedRows().length; i++) {
                    int selectedRow = detailsTable.getSelectedRows()[i];
                    ArrayList<NaemTec> tecs = (ArrayList<NaemTec>) DataManager.getObject(VariableNames.TEC_NAEM_USING_ROWS);
                    NaemTec tec = tecs.get(selectedRow);
                    if (tec.getMoneyIn() == 2) {
                        tec.setMoneyIn(0);
                    } else {
                        tec.setMoneyIn(2);
                    }
                }
                saveButton.setEnabled(true);
                model.fireTableDataChanged();
            }
        });
        markNaemMoneyNadoButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/nadoZapl.png")));
        markNaemMoneyNadoButton.setFocusPainted(false);
        markNaemMoneyNadoButton.setEnabled(false);
        markNaemMoneyNadoButton.setToolTipText("Надо оплатить, деньги пришли");
        DataManager.setObject(VariableNames.UI_TOP_PANEL_MARK_NAEM_PAID_NAM_NADO_BUTTON, markNaemMoneyNadoButton);
        markNaemMoneyNadoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel model = (DefaultTableModel) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_MODEL);
                JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_TABLE);
                for (int i = 0; i < detailsTable.getSelectedRows().length; i++) {
                    int selectedRow = detailsTable.getSelectedRows()[i];
                    ArrayList<NaemTec> tecs = (ArrayList<NaemTec>) DataManager.getObject(VariableNames.TEC_NAEM_USING_ROWS);
                    NaemTec tec = tecs.get(selectedRow);
                    if (tec.getMoneyIn() == 1) {
                        tec.setMoneyIn(0);
                    } else {
                        tec.setMoneyIn(1);
                    }
                }
                saveButton.setEnabled(true);
                model.fireTableDataChanged();
            }
        });


        JLabel toplivoLabel = new JLabel("дизель цена:");
        toplivoField = new JTextField();
        toplivoField.setMaximumSize(new Dimension(95, 20));
        toplivoField.setPreferredSize(new Dimension(95, 20));
        toplivoField.setMinimumSize(new Dimension(95, 20));
        toplivoField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                saveToplivoButton.setEnabled(true);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                if (toplivoField.getText().isEmpty()) {
                    saveToplivoButton.setEnabled(false);
                } else {
                    saveToplivoButton.setEnabled(true);
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });

        DataManager.setObject(VariableNames.UI_TOPLIVO_FIELD, toplivoField);
        saveToplivoButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/save_toplivo.png")));
        saveToplivoButton.setFocusPainted(false);
        saveToplivoButton.setEnabled(false);
        saveToplivoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    try {
                        Double.valueOf(toplivoField.getText());
                    } catch (IllegalArgumentException e1) {
                        JOptionPane.showOptionDialog(null, "Цена может быть только числами.\n Проверьте введеное значение", "Неверно введены данные!!!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                        return;
                    }
                    File file = new File(VariableNames.PATH_TO_INFO);
                    InputStream in = new FileInputStream(file);
                    HSSFWorkbook wb = new HSSFWorkbook(in);
                    ExcelExtractor extractor = new ExcelExtractor(wb);
                    extractor.setFormulasNotResults(false); // Считать формулы
                    HSSFSheet sheet = wb.getSheet("техника");
                    for (int i = 0; i < 20; i++) {
                        if (sheet.getRow(0).getCell(i) != null) {
                            if (sheet.getRow(0).getCell(i).toString().equals("дизель цена")) {
                                DataManager.setObject(VariableNames.TOPLIVO_COST, toplivoField.getText());
                                sheet.getRow(0).getCell(i + 1).setCellValue(Double.valueOf(toplivoField.getText()));
                                break;
                            }
                        }
                    }
                    FileOutputStream fileOut = new FileOutputStream(VariableNames.PATH_TO_INFO);
                    wb.write(fileOut);
                    fileOut.close();
                    JOptionPane.showMessageDialog(null, "Изменение успешно сохранены\nСтоимость топлива изменина на: " + toplivoField.getText(), "Изменения сохранены", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
                } catch (IOException e1) {
                    JOptionPane.showOptionDialog(null, "Нет доступа к базе данных. Она используется другой программой.\n Закройте все программы которые могут использовать ее (скорее всего это excel)", "данные не изменены", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                }
            }
        });

//        add(userButton, new GBC(0, 0).setInsets(20, 0));
        add(toplivoLabel, new GBC(0, 0).setInsets(25, 7, 0, 0).setAnchor(GBC.WEST));
        add(toplivoField, new GBC(0, 0).setInsets(25, 80, 0, 0).setAnchor(GBC.WEST));
        add(saveToplivoButton, new GBC(1, 0).setInsets(25, 3, 0, 0).setAnchor(GBC.WEST));
        add(tecButton, new GBC(0, 1).setInsets(20, 0, 0, 0).setAnchor(GBC.WEST));
        add(addRowButton, new GBC(1, 1).setInsets(20, 0, 0, 0).setAnchor(GBC.WEST));
        add(removeButton, new GBC(2, 1, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(saveButton, new GBC(3, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(exlButton, new GBC(4, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(updateButton, new GBC(5, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(markOurButton, new GBC(6, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(markNaemPaidNamButton, new GBC(6, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(markNaemMoneyOkButton, new GBC(7, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
        add(markNaemMoneyNadoButton, new GBC(8, 0, 1, 2).setInsets(0, 7).setAnchor(GBC.SOUTH));
    }


    public static void saveNewExcelAction() {
        final JFileChooser fileChooser = new JFileChooser();
        MSExcelFilter msExcelFilter = new MSExcelFilter();
        fileChooser.addChoosableFileFilter(msExcelFilter);
        fileChooser.setFileFilter(msExcelFilter);
        int rc = fileChooser.showSaveDialog(null);
        int response;
        while (rc == JFileChooser.APPROVE_OPTION && !FileHelper.verifyFileName(fileChooser.getCurrentDirectory(), fileChooser.getSelectedFile())) {
            response = JOptionPane.showOptionDialog(null, "Файл " + fileChooser.getSelectedFile() + " Уже существует. Хотите заменить его? ", "Сохранить", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
            if (response == JOptionPane.NO_OPTION) {
                rc = fileChooser.showSaveDialog(null);
            }
            if (response == JOptionPane.YES_OPTION) {
                rc = JFileChooser.CANCEL_OPTION;
            }
        }
        File file = fileChooser.getSelectedFile();
        if (file != null) {
            fileChooser.getComponentListeners();
            FileHelper.createResultExcelFile(file);
        } else {
            return;
        }

    }
}
